#include "njm_window.hpp"

#include <stdexcept>

namespace njm {
    NjmWindow::NjmWindow(int w, int h, std::string name) : width{w}, height{h}, windowName{name}
    {
        initWindow();
    }   
    
    NjmWindow::~NjmWindow()
    {
        glfwDestroyWindow(window);
        glfwTerminate();
    }

    void NjmWindow::initWindow()
    {
        glfwInit();
        glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
        glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);

        window = glfwCreateWindow(width, height, windowName.c_str(), nullptr, nullptr);
        glfwSetWindowUserPointer(window, this);
        glfwSetFramebufferSizeCallback(window, framebufferResizeCallback);
    }

    void NjmWindow::framebufferResizeCallback(GLFWwindow *window, int width, int height)
    {
        auto pWindow = static_cast<NjmWindow *>(glfwGetWindowUserPointer(window));
        pWindow->width = width;
        pWindow->height = height;
        pWindow->framebufferResized = true;
    }

    bool NjmWindow::shouldClose()
    {
        return glfwWindowShouldClose(window);
    }

    void NjmWindow::createWindowSurface(VkInstance instance, VkSurfaceKHR *surface)
    {
        if (glfwCreateWindowSurface(instance, window, nullptr, surface) != VK_SUCCESS)
        {
            throw std::runtime_error("failed to create window-surface");
        }
    }
}